<template>
  <div class="login">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin" class="login-form">
      <!-- 角色选择 -->
      <div class="form-group">
        <label>选择角色</label>
        <div class="role-selector">
          <div 
            class="role-option" 
            :class="{ active: credentials.role === 'parent' }"
            @click="credentials.role = 'parent'"
          >
            <i class="icon">👨‍👩‍👧‍👦</i>
            <span>我是家长</span>
          </div>
          <div 
            class="role-option" 
            :class="{ active: credentials.role === 'child' }"
            @click="credentials.role = 'child'"
          >
            <i class="icon">👶</i>
            <span>我是孩子</span>
          </div>
        </div>
      </div>

      <div class="form-group">
        <label>用户名</label>
        <input type="text" v-model="credentials.username" required>
      </div>
      <div class="form-group">
        <label>密码</label>
        <input type="password" v-model="credentials.password" required>
      </div>
      <button type="submit">登录</button>
      <p class="register-link">
        还没有账号？<router-link to="/register">立即注册</router-link>
      </p>
    </form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'Login',
  data() {
    return {
      credentials: {
        role: 'parent',  // 默认选择家长角色
        username: '',
        password: ''
      }
    }
  },
  methods: {
    async handleLogin() {
      try {
        const response = await axios.post('/api/auth/login', this.credentials)
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('userId', response.data.user_id)
        localStorage.setItem('userRole', response.data.role)
        
        // 根据角色跳转到不同页面
        if (response.data.role === 'parent') {
          this.$router.push('/children')
        } else {
          this.$router.push(`/habits/${response.data.user_id}`)
        }
      } catch (error) {
        console.error('登录失败:', error)
        alert('登录失败，请检查用户名和密码')
      }
    }
  }
}
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 40px auto;
  padding: 20px;
}

.login-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.register-link {
  margin-top: 15px;
  text-align: center;
}

.role-selector {
  display: flex;
  gap: 20px;
  margin-top: 10px;
}

.role-option {
  flex: 1;
  padding: 15px;
  border: 2px solid #ddd;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.role-option.active {
  border-color: #42b983;
  background-color: #f0f9f4;
}

.role-option .icon {
  font-size: 24px;
  display: block;
  margin-bottom: 8px;
}
</style> 